﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Xml;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using CS = System.Configuration.ConfigurationManager;
using System.Xml.Schema;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

namespace IOPPDExcel2XML
{
    public partial class Form1 : Form
    {

        DateTime periodOd = DateTime.Now;
        DateTime periodDo = DateTime.Now;
        int ukupnoZaposlenih = 0;
        int UkupnoBrojLica = 0;
        int mjesec = 0, godina = 0;

        static string poslodavacPIB = CS.AppSettings["poslodavacPIB"];
        static string poslodavacNaziv = CS.AppSettings["poslodavacNaziv"];
        static string poslodavacPunNaziv = CS.AppSettings["poslodavacPunNaziv"];
        static string poslodavacTelefon = CS.AppSettings["poslodavacTelefon"];
        static string poslodavacEmail = CS.AppSettings["poslodavacEmail"];
        static string brojZaposlenihInvalida = CS.AppSettings["brojZaposlenihInvalida"];
        static string formatDatuma = CS.AppSettings["formatDatuma"];
        static string podnosilacPIB = CS.AppSettings["podnosilacPIB"];

        static int poljeJMBG = Convert.ToInt32(CS.AppSettings["poljeJMBG"]);
        static int poljeIme = Convert.ToInt32(CS.AppSettings["poljeIme"]);
        static int poljeSifra = Convert.ToInt32(CS.AppSettings["poljeSifra"]);
        static int poljePeriodOD = Convert.ToInt32(CS.AppSettings["poljePeriodOD"]);
        static int poljePeriodDO = Convert.ToInt32(CS.AppSettings["poljePeriodDO"]);
        static int poljeBruto = Convert.ToInt32(CS.AppSettings["poljeBruto"]);
        static int poljeTOsigPorez = Convert.ToInt32(CS.AppSettings["poljeTOsigPorez"]);
        static int poljeTOsigPIO = Convert.ToInt32(CS.AppSettings["poljeTOsigPIO"]);
        static int poljeTOsigRFZO = Convert.ToInt32(CS.AppSettings["poljeTOsigRFZO"]);
        static int poljeTOsigZZZ = Convert.ToInt32(CS.AppSettings["poljeTOsigZZZ"]);
        static int poljeTIsplatPIO = Convert.ToInt32(CS.AppSettings["poljeTIsplatPIO"]);
        static int poljeTIsplatRFZO = Convert.ToInt32(CS.AppSettings["poljeTIsplatRFZO"]);
        static int poljeTIsplatZZZ = Convert.ToInt32(CS.AppSettings["poljeTIsplatZZZ"]);
        static int poljeTIsplatFondRada = Convert.ToInt32(CS.AppSettings["poljeTIsplatFondRada"]);

        static int poljeGodina = Convert.ToInt32(CS.AppSettings["poljeGodina"]);
        static bool poljeGodinaPosebno = Convert.ToBoolean(CS.AppSettings["poljeGodinaPosebno"]);
        
        static string poljeFormatDatuma = CS.AppSettings["formatDatuma"];
        static string[] sifreZarada = CS.AppSettings["sifreZarada"].Split(';');

        public Form1()
        {
            InitializeComponent();
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (System.Exception ex)
            {
                obj = null;
                Console.WriteLine(ex);
            }
            finally
            {
                GC.Collect();
            }
        }

        private static void Handler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
                System.Diagnostics.Trace.WriteLine(
                   String.Format("Line: {0}, Position: {1} \"{2}\"",
                      e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));

        }

        public class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding
            {
                get { return Encoding.UTF8; }
            }
        }

        private static void ValidationCallBack(object sender, ValidationEventArgs args)
        {
            //if (args.Severity == XmlSeverityType.Warning)
            //    Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
            //else
            MessageBox.Show(args.Message);
            //Console.WriteLine("\tValidation error: " + args.Message);
        }

        private void RefreshConfig()
        {
            CS.RefreshSection("appSettings");
            poslodavacPIB = CS.AppSettings["poslodavacPIB"];
            poslodavacNaziv = CS.AppSettings["poslodavacNaziv"];
            poslodavacPunNaziv = CS.AppSettings["poslodavacPunNaziv"];
            poslodavacTelefon = CS.AppSettings["poslodavacTelefon"];
            poslodavacEmail = CS.AppSettings["poslodavacEmail"];
            brojZaposlenihInvalida = CS.AppSettings["brojZaposlenihInvalida"];
            formatDatuma = CS.AppSettings["formatDatuma"];
            podnosilacPIB = CS.AppSettings["podnosilacPIB"];

            poljeJMBG = Convert.ToInt32(CS.AppSettings["poljeJMBG"]);
            poljeIme = Convert.ToInt32(CS.AppSettings["poljeIme"]);
            poljeSifra = Convert.ToInt32(CS.AppSettings["poljeSifra"]);
            poljePeriodOD = Convert.ToInt32(CS.AppSettings["poljePeriodOD"]);
            poljePeriodDO = Convert.ToInt32(CS.AppSettings["poljePeriodDO"]);
            poljeBruto = Convert.ToInt32(CS.AppSettings["poljeBruto"]);
            poljeTOsigPorez = Convert.ToInt32(CS.AppSettings["poljeTOsigPorez"]);
            poljeTOsigPIO = Convert.ToInt32(CS.AppSettings["poljeTOsigPIO"]);
            poljeTOsigRFZO = Convert.ToInt32(CS.AppSettings["poljeTOsigRFZO"]);
            poljeTOsigZZZ = Convert.ToInt32(CS.AppSettings["poljeTOsigZZZ"]);
            poljeTIsplatPIO = Convert.ToInt32(CS.AppSettings["poljeTIsplatPIO"]);
            poljeTIsplatRFZO = Convert.ToInt32(CS.AppSettings["poljeTIsplatRFZO"]);
            poljeTIsplatZZZ = Convert.ToInt32(CS.AppSettings["poljeTIsplatZZZ"]);
            poljeTIsplatFondRada = Convert.ToInt32(CS.AppSettings["poljeTIsplatFondRada"]);

            poljeGodina = Convert.ToInt32(CS.AppSettings["poljeGodina"]);
            poljeGodinaPosebno = Convert.ToBoolean(CS.AppSettings["poljeGodinaPosebno"]);
        
            poljeFormatDatuma = CS.AppSettings["formatDatuma"];
        }

        private void btnUvoz_Click(object sender, EventArgs e)
        {
            //System.Windows.Forms.OpenFileDialog fileBrowser = new System.Windows.Forms.OpenFileDialog();
            DialogResult dlgResult = fileBrowser.ShowDialog();

            //decimal TeretOsiguraonikaPorez = 0;
            rtbXML.Enabled = false;
            rtbXML.Text = "";
            string pomJmbg = String.Empty;
            string pomPrezimeIIme = String.Empty;
            DateTime dt = DateTime.Now;

            string vrpoljeJMBG = "";
            string vrpoljeIme = "";
            string vrpoljeSifra = "";
            string vrpoljePeriodOD = "";
            string vrpoljePeriodDO = "";
            decimal vrpoljeBruto = 0;
            decimal vrpoljeTOsigPorez = 0;
            decimal vrpoljeTOsigPIO = 0;
            decimal vrpoljeTOsigRFZO = 0;
            decimal vrpoljeTOsigZZZ = 0;
            decimal vrpoljeTIsplatPIO = 0;
            decimal vrpoljeTIsplatRFZO = 0;
            decimal vrpoljeTIsplatZZZ = 0;
            decimal vrpoljeTIsplatFondRada = 0;

            Excel.Application app = new Excel.Application();
            app.DisplayAlerts = false;
            Excel.Workbook workbook = null;
            Excel.Worksheet worksheet = null;

            dgvStart.Rows.Clear();

            if (dlgResult == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    tabControl1.SelectedTab = tabDataGrid;

                    RefreshConfig();
                    
                    string Putanja = fileBrowser.FileName;
                    txtFileName.Text = fileBrowser.FileName;
                    txtFileName.Enabled = false;

                    
                    workbook = app.Workbooks.Open(Putanja);

                    worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);

                    Excel.Range usedRange = worksheet.UsedRange;

                    //uzimam prvi WorkSheet (u ovom slucaju "Ukupno"
                    worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);

                    usedRange = worksheet.UsedRange;

                    dgvStart.ColumnCount = 14;
                    dgvStart.Columns[0].HeaderText = "JMBG";
                    dgvStart.Columns[1].HeaderText = "Prezime i ime";
                    dgvStart.Columns[2].HeaderText = "Datum OD";
                    dgvStart.Columns[3].HeaderText = "Datum DO";
                    dgvStart.Columns[4].HeaderText = "Šifra";
                    dgvStart.Columns[5].HeaderText = "Bruto";
                    dgvStart.Columns[6].HeaderText = "TOsigPorez";
                    dgvStart.Columns[7].HeaderText = "TOsigPIO";
                    dgvStart.Columns[8].HeaderText = "TOsigRFZO";
                    dgvStart.Columns[9].HeaderText = "TOsigZZZ";
                    dgvStart.Columns[10].HeaderText = "TIsplatPIO";
                    dgvStart.Columns[11].HeaderText = "TIsplatRFZO";
                    dgvStart.Columns[12].HeaderText = "TIsplatZZZ";
                    dgvStart.Columns[13].HeaderText = "TIsplatFondRada";

                    int pos;
                    List<string> spisakJMBG = new List<string>();

                    
                    //dgvStart.Columns[14].HeaderText = "Naziv";
                    int brojac=0;
                    foreach (Excel.Range row in usedRange.Rows)
                    {
                        if (row.Cells[1, poljeJMBG].Value2 != null && row.Cells[1, poljeJMBG].Value2.ToString().Trim().Length == 13)
                        {
                            brojac++;

                            vrpoljeJMBG = row.Cells[1, poljeJMBG].Value2.ToString().Trim();
                            vrpoljeIme = row.Cells[1, poljeIme].Value2.ToString().Trim();
                            vrpoljeSifra = row.Cells[1, poljeSifra].Value2.ToString().Trim();
                            if (poljeGodinaPosebno)
                            {
                                vrpoljePeriodOD = row.Cells[1, poljePeriodOD].Value2.ToString().Trim() + '.' + row.Cells[1, poljeGodina].Value2.ToString().Trim();
                                vrpoljePeriodDO = row.Cells[1, poljePeriodDO].Value2.ToString().Trim() + '.' + row.Cells[1, poljeGodina].Value2.ToString().Trim();
                            }
                            else
                            {
                                vrpoljePeriodOD = row.Cells[1, poljePeriodOD].Value2.ToString().Trim();
                                vrpoljePeriodDO = row.Cells[1, poljePeriodDO].Value2.ToString().Trim();
                            }
                            vrpoljePeriodOD = vrpoljePeriodOD.Replace("..", ".");
                            vrpoljePeriodDO = vrpoljePeriodDO.Replace("..", ".");

                            
                            if (brojac == 1)
                            {
                                try
                                {
                                    dt = DateTime.ParseExact(Regex.Replace(vrpoljePeriodOD, @"\s+", ""), txtFormatDatuma.Text, System.Globalization.CultureInfo.InvariantCulture);
                                }
                                catch (System.FormatException)
                                {
                                    MessageBox.Show("Pogrešan format datuma!");
                                    break;
                                }
                            }
                            vrpoljeBruto = Convert.ToDecimal(row.Cells[1, poljeBruto].Value2.ToString());
                            vrpoljeTOsigPorez = Convert.ToDecimal(row.Cells[1, poljeTOsigPorez].Value2.ToString());
                            vrpoljeTOsigPIO = Convert.ToDecimal(row.Cells[1, poljeTOsigPIO].Value2.ToString());
                            vrpoljeTOsigRFZO = Convert.ToDecimal(row.Cells[1, poljeTOsigRFZO].Value2.ToString());
                            vrpoljeTOsigZZZ = Convert.ToDecimal(row.Cells[1, poljeTOsigZZZ].Value2.ToString());
                            vrpoljeTIsplatPIO = Convert.ToDecimal(row.Cells[1, poljeTIsplatPIO].Value2.ToString());
                            vrpoljeTIsplatRFZO = Convert.ToDecimal(row.Cells[1, poljeTIsplatRFZO].Value2.ToString());
                            vrpoljeTIsplatZZZ = Convert.ToDecimal(row.Cells[1, poljeTIsplatZZZ].Value2.ToString());
                            vrpoljeTIsplatFondRada = Convert.ToDecimal(row.Cells[1, poljeTIsplatFondRada].Value2.ToString());

                            dgvStart.Rows.Add(vrpoljeJMBG, vrpoljeIme, Regex.Replace(vrpoljePeriodOD, @"\s+", "").Replace("..", "."), Regex.Replace(vrpoljePeriodDO, @"\s+", "").Replace("..", "."), vrpoljeSifra, vrpoljeBruto, 
                            vrpoljeTOsigPorez, vrpoljeTOsigPIO, vrpoljeTOsigRFZO, vrpoljeTOsigZZZ, vrpoljeTIsplatPIO, vrpoljeTIsplatRFZO,
                            vrpoljeTIsplatZZZ, vrpoljeTIsplatFondRada);

                            pos = Array.IndexOf(sifreZarada, Convert.ToInt32(vrpoljeSifra).ToString());
                            if (pos > -1)
                            {
                                spisakJMBG.Add(vrpoljeJMBG);                                
                            }
                            
                        }
                                       
                        mjesec = dt.Month;
                        txtMjesec.Text = mjesec.ToString();
                        godina = dt.Year;
                        txtGodina.Text = godina.ToString();
                        txtProsjecnaZarada.Text = CS.AppSettings["PZ"+godina.ToString()];
                    }

                    var distinctJMBG = (from d in spisakJMBG select d).Distinct();
                    UkupnoBrojLica = distinctJMBG.Count();
                    txtBrZaposlenih.Text = UkupnoBrojLica.ToString();

                }
                catch (Exception exc)
                {
                    rtbXML.Text = exc.ToString();
                }
                finally
                {
                    app.Quit();
                    releaseObject(workbook); //GC za workbook
                    releaseObject(worksheet); //GC za worksheet
                    app = null;
                    btnCovertToXML.Enabled = true;
                }
            }
        }

        private void btnCovertToXML_Click(object sender, EventArgs e)
        {

            try
            {
                XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
                {
                    Indent = true,
                    IndentChars = "   ",
                    NewLineOnAttributes = false
                };

                using (TextWriter writer = new Utf8StringWriter())
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(writer, xmlWriterSettings))
                    {
                        xmlWriter.WriteStartElement("Izvjestaj", "urn:IOPD_V1_0.xsd");
                        xmlWriter.WriteStartElement("Zaglavlje");
                        xmlWriter.WriteStartElement("ObracunskiPeriodMjesec");
                        xmlWriter.WriteValue(mjesec.ToString());
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("ObracunskiPeriodGodina");
                        xmlWriter.WriteValue(godina.ToString());
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Podnosilac");
                        xmlWriter.WriteStartElement("Podnosilac-PIB");
                        xmlWriter.WriteValue(txtPodnosilac.Text);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Sluzbenik");
                        xmlWriter.WriteStartElement("Sluzbenik-DatumPrijema");
                        xmlWriter.WriteValue(DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz"));
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();

                        xmlWriter.WriteStartElement("Poslodavac");
                        xmlWriter.WriteStartElement("Poslodavac-PIB");
                        xmlWriter.WriteValue(txtPoslodavacPIB.Text);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Poslodavac-Naziv");
                        xmlWriter.WriteValue(txtPoslodavacNaziv.Text);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Poslodavac-Telefon");
                        xmlWriter.WriteValue(txtPoslodavacTel.Text);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Poslodavac-Email");
                        xmlWriter.WriteValue(txtPoslodavacEmail.Text);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Poslodavac-PunNaziv");
                        xmlWriter.WriteValue(txtPoslodavacPunNaziv.Text);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();


                        decimal ukporez = 0, ukpio = 0, ukrfzo = 0, ukzzz = 0,
                            ukipio = 0, ukirfzo = 0, ukizzz = 0, ukifondrada = 0, ukbruto = 0;

                        ukupnoZaposlenih = Convert.ToInt32(txtBrZaposlenih.Text);
                        foreach (DataGridViewRow row in dgvStart.Rows)
                        {
                            ukbruto += Convert.ToDecimal(row.Cells[5].Value.ToString());
                            ukporez += Convert.ToDecimal(row.Cells[6].Value.ToString());
                            ukpio += Convert.ToDecimal(row.Cells[7].Value.ToString());
                            ukrfzo += Convert.ToDecimal(row.Cells[8].Value.ToString());
                            ukzzz += Convert.ToDecimal(row.Cells[9].Value.ToString());
                            ukipio += Convert.ToDecimal(row.Cells[10].Value.ToString());
                            ukirfzo += Convert.ToDecimal(row.Cells[11].Value.ToString());
                            ukizzz += Convert.ToDecimal(row.Cells[12].Value.ToString());
                            ukifondrada += Convert.ToDecimal(row.Cells[13].Value.ToString());

                            //if (Convert.ToDecimal(row.Cells[4].Value.ToString()) < 20) ukupnoZaposlenih++;

                        }

                        xmlWriter.WriteStartElement("Ukupno");
                        xmlWriter.WriteStartElement("Ukupno-BrojLica");
                        xmlWriter.WriteValue(txtBrZaposlenih.Text);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Ukupno-BrutoIznos");
                        xmlWriter.WriteValue(ukbruto.ToString("F"));
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("TeretOsiguraonika");
                        xmlWriter.WriteStartElement("TeretOsiguraonika-Porez");
                        xmlWriter.WriteValue(ukporez);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("TeretOsiguraonika-PIO");
                        xmlWriter.WriteValue(ukpio);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("TeretOsiguraonika-RFZO");
                        xmlWriter.WriteValue(ukrfzo);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("TeretOsiguraonika-ZZZ");
                        xmlWriter.WriteValue(ukzzz);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("TeretIsplatioca");
                        xmlWriter.WriteStartElement("TeretIsplatioca-PIO");
                        xmlWriter.WriteValue(ukipio);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("TeretIsplatioca-RFZO");
                        xmlWriter.WriteValue(ukirfzo);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("TeretIsplatioca-ZZZ");
                        xmlWriter.WriteValue(ukizzz);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("TeretIsplatioca-FondRada");
                        xmlWriter.WriteValue(ukifondrada);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();


                        //xmlWriter.WriteStartElement("UkupnoBrojLicaUK");
                        //xmlWriter.WriteValue(dgvStart.RowCount.ToString());
                        //xmlWriter.WriteEndElement();

                        int brojac = 0;
                        string osnovID;
                        string osnovNaziv;
                        decimal prosjecnaMjesecnaPlata = 724;
                        //petlja kroz dataset za pojedinachne unose
                        xmlWriter.WriteStartElement("PojedinacniObracun");
                        foreach (DataGridViewRow row in dgvStart.Rows)
                        {
                            DateTime dateOD = DateTime.ParseExact(row.Cells[2].Value.ToString(), txtFormatDatuma.Text,
                                       System.Globalization.CultureInfo.InvariantCulture);
                            DateTime dateDO = DateTime.ParseExact(row.Cells[3].Value.ToString(), txtFormatDatuma.Text,
                                       System.Globalization.CultureInfo.InvariantCulture);
                            if (Convert.ToDecimal(row.Cells[5].Value.ToString()) > 0)
                            {
                                try
                                {
                                    osnovID=Convert.ToInt32(row.Cells[4].Value.ToString()).ToString();
                                    osnovNaziv = CS.AppSettings[osnovID];
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("U konfiguraciji nije pronadjen naziv za osnovicu " + row.Cells[5].Value.ToString());
                                    osnovNaziv = "Zarada";
                                }                                 
                                
                                brojac++;
                                xmlWriter.WriteStartElement("Unos");
                                xmlWriter.WriteStartElement("Unos-PIB");
                                xmlWriter.WriteValue(row.Cells[0].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-PrezimeIIme");
                                xmlWriter.WriteValue(row.Cells[1].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-OsnovID");
                                xmlWriter.WriteValue(row.Cells[4].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Index");
                                xmlWriter.WriteValue(brojac.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-Osnov");
                                xmlWriter.WriteValue(osnovNaziv);
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-PeriodOd");
                                xmlWriter.WriteValue(dateOD.ToString("yyyy-MM-ddThh:mm:sszzz"));
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-PeriodDo");
                                xmlWriter.WriteValue(dateDO.ToString("yyyy-MM-ddThh:mm:sszzz"));
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-BrutoOsnov");
                                xmlWriter.WriteValue(row.Cells[5].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-TeretOsiguranikaPorez");
                                xmlWriter.WriteValue(row.Cells[6].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-TeretOsiguranikaPIO");
                                xmlWriter.WriteValue(row.Cells[7].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-TeretOsiguranikaRFZO");
                                xmlWriter.WriteValue(row.Cells[8].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-TeretOsiguranikaZZZ");
                                xmlWriter.WriteValue(row.Cells[9].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-TeretIsplatiocaPIO");
                                xmlWriter.WriteValue(row.Cells[10].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-TeretIsplatiocaRFZO");
                                xmlWriter.WriteValue(row.Cells[11].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-TeretIsplatiocaZZZ");
                                xmlWriter.WriteValue(row.Cells[12].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteStartElement("Unos-TeretIsplatiocaFondRada");
                                xmlWriter.WriteValue(row.Cells[13].Value.ToString());
                                xmlWriter.WriteEndElement();
                                xmlWriter.WriteEndElement();
                            }

                        }
                        xmlWriter.WriteEndElement();

                        int brojInvalidaKojeTrebaZaposliti = 0;
                        decimal osnovica = 0, iznos = 0;
                        int stopaInvalidi = 0;
                        try
                        {
                            prosjecnaMjesecnaPlata = Convert.ToDecimal(txtProsjecnaZarada.Text);
                        }
                        catch (FormatException fex)
                        {
                            MessageBox.Show("Nije definisana prosječna zarada za " + txtGodina.Text + ". godinu. Postavljam podrazumijevanu vrijednost - 724.");
                            prosjecnaMjesecnaPlata = 724;
                        }                        

                        if (ukupnoZaposlenih <= 10)
                        {
                            ukupnoZaposlenih = 0;
                        }
                        if (ukupnoZaposlenih > 10 && ukupnoZaposlenih < 20)
                        {
                            stopaInvalidi = 5;
                            brojInvalidaKojeTrebaZaposliti = 1;
                        }
                        else if (ukupnoZaposlenih >= 20 && ukupnoZaposlenih <= 50)
                        {
                            stopaInvalidi = 20;
                            brojInvalidaKojeTrebaZaposliti = 1;
                        }
                        else if (ukupnoZaposlenih > 50)
                        {
                            stopaInvalidi = 20;
                            brojInvalidaKojeTrebaZaposliti = (int)Math.Round(ukupnoZaposlenih * Convert.ToDecimal(0.05));
                        }
                        osnovica = brojInvalidaKojeTrebaZaposliti * prosjecnaMjesecnaPlata;
                        iznos = (decimal)osnovica * ((decimal)stopaInvalidi / 100);

                        if (brojInvalidaKojeTrebaZaposliti <= Convert.ToInt32(txtBrojInvalida.Text)) iznos = 0;

                        // Doprinos Zbog Nezaposljavanja Invalida
                        xmlWriter.WriteStartElement("DoprinosZbogNezaposljavanjaInvalida");
                        xmlWriter.WriteStartElement("UkupanBrojZaposlenih");
                        xmlWriter.WriteValue(ukupnoZaposlenih);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("BrojZaposlenihInvalida");
                        xmlWriter.WriteValue(txtBrojInvalida.Text);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Osnovica");
                        xmlWriter.WriteValue(osnovica.ToString("F"));
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Stopa");
                        xmlWriter.WriteValue(stopaInvalidi);
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteStartElement("Iznos");
                        xmlWriter.WriteValue(iznos.ToString("F"));
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndElement();

                    }
                    rtbXML.Text = writer.ToString();
                    rtbXML.Enabled = true;
                    tabControl1.SelectedTab = tabXML;
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var version = Application.ProductVersion; 
            lblVerzija.Text = String.Format("Verzija {0}", version);

            txtPodnosilac.Text = podnosilacPIB;
            txtPoslodavacNaziv.Text = poslodavacNaziv;
            txtPoslodavacPIB.Text = poslodavacPIB;
            txtPoslodavacEmail.Text = poslodavacEmail;
            txtPoslodavacPunNaziv.Text = poslodavacPunNaziv;
            txtPoslodavacTel.Text = poslodavacTelefon;
            txtBrojInvalida.Text = brojZaposlenihInvalida;

            txtPoljeJMBG.Text = poljeJMBG.ToString();
            txtPoljeIme.Text = poljeIme.ToString();
            txtPoljeSifra.Text = poljeSifra.ToString();
            txtPoljeOD.Text = poljePeriodOD.ToString();
            txtPoljeDO.Text = poljePeriodDO.ToString();
            txtPoljeBruto.Text = poljeBruto.ToString();
            txtPoljeOporez.Text = poljeTOsigPorez.ToString();
            txtPoljeOPIO.Text = poljeTOsigPIO.ToString();
            txtPoljeORFZO.Text = poljeTOsigRFZO.ToString();
            txtPoljeOZZZ.Text = poljeTOsigZZZ.ToString();
            txtPoljeIPIO.Text = poljeTIsplatPIO.ToString();
            txtPoljeIRFZO.Text = poljeTIsplatRFZO.ToString();
            txtPoljeIZZZ.Text = poljeTIsplatZZZ.ToString();
            txtPoljeIFondrada.Text = poljeTIsplatFondRada.ToString();
            txtGodinaConfig.Text = poljeGodina.ToString();
            chkGodinaOdvojena.Checked = poljeGodinaPosebno;

            txtFormatDatuma.Text = poljeFormatDatuma.ToString();
        }

        private void btnIzmijeniZaglavlje_Click(object sender, EventArgs e)
        {
            SacuvajIzmjeneConfiga();
        }

        private void SacuvajIzmjeneConfiga()
        {
            try
            {
                System.Configuration.Configuration config = CS.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

                config.AppSettings.Settings.Remove("podnosilacPIB");
                config.AppSettings.Settings.Add("podnosilacPIB", txtPodnosilac.Text);

                config.AppSettings.Settings.Remove("poslodavacNaziv");
                config.AppSettings.Settings.Add("poslodavacNaziv", txtPoslodavacNaziv.Text);

                config.AppSettings.Settings.Remove("poslodavacPIB");
                config.AppSettings.Settings.Add("poslodavacPIB", txtPoslodavacPIB.Text);

                config.AppSettings.Settings.Remove("poslodavacEmail");
                config.AppSettings.Settings.Add("poslodavacEmail", txtPoslodavacEmail.Text);

                config.AppSettings.Settings.Remove("poslodavacPunNaziv");
                config.AppSettings.Settings.Add("poslodavacPunNaziv", txtPoslodavacPunNaziv.Text);

                config.AppSettings.Settings.Remove("poslodavacTelefon");
                config.AppSettings.Settings.Add("poslodavacTelefon", txtPoslodavacTel.Text);

                config.AppSettings.Settings.Remove("brojZaposlenihInvalida");
                config.AppSettings.Settings.Add("brojZaposlenihInvalida", txtBrojInvalida.Text);

                config.AppSettings.Settings.Remove("poljeJMBG");
                config.AppSettings.Settings.Add("poljeJMBG", txtPoljeJMBG.Text);

                config.AppSettings.Settings.Remove("poljeIme");
                config.AppSettings.Settings.Add("poljeIme", txtPoljeIme.Text);

                config.AppSettings.Settings.Remove("poljeSifra");
                config.AppSettings.Settings.Add("poljeSifra", txtPoljeSifra.Text);

                config.AppSettings.Settings.Remove("poljePeriodOD");
                config.AppSettings.Settings.Add("poljePeriodOD", txtPoljeOD.Text);

                config.AppSettings.Settings.Remove("poljePeriodDO");
                config.AppSettings.Settings.Add("poljePeriodDO", txtPoljeDO.Text);

                config.AppSettings.Settings.Remove("poljeBruto");
                config.AppSettings.Settings.Add("poljeBruto", txtPoljeBruto.Text);

                config.AppSettings.Settings.Remove("poljeTOsigPorez");
                config.AppSettings.Settings.Add("poljeTOsigPorez", txtPoljeOporez.Text);

                config.AppSettings.Settings.Remove("poljeTOsigPIO");
                config.AppSettings.Settings.Add("poljeTOsigPIO", txtPoljeOPIO.Text);

                config.AppSettings.Settings.Remove("poljeTOsigRFZO");
                config.AppSettings.Settings.Add("poljeTOsigRFZO", txtPoljeORFZO.Text);

                config.AppSettings.Settings.Remove("poljeTOsigZZZ");
                config.AppSettings.Settings.Add("poljeTOsigZZZ", txtPoljeOZZZ.Text);

                config.AppSettings.Settings.Remove("poljeTIsplatPIO");
                config.AppSettings.Settings.Add("poljeTIsplatPIO", txtPoljeIPIO.Text);

                config.AppSettings.Settings.Remove("poljeTIsplatRFZO");
                config.AppSettings.Settings.Add("poljeTIsplatRFZO", txtPoljeIRFZO.Text);

                config.AppSettings.Settings.Remove("poljeTIsplatZZZ");
                config.AppSettings.Settings.Add("poljeTIsplatZZZ", txtPoljeIZZZ.Text);

                config.AppSettings.Settings.Remove("poljeTIsplatFondRada");
                config.AppSettings.Settings.Add("poljeTIsplatFondRada", txtPoljeIFondrada.Text);

                config.AppSettings.Settings.Remove("formatDatuma");
                config.AppSettings.Settings.Add("formatDatuma", txtFormatDatuma.Text);

                config.AppSettings.Settings.Remove("poljeGodina");
                config.AppSettings.Settings.Add("poljeGodina", txtGodinaConfig.Text);

                config.AppSettings.Settings.Remove("poljeGodinaPosebno");
                config.AppSettings.Settings.Add("poljeGodinaPosebno", chkGodinaOdvojena.Checked.ToString());

                config.Save();

                poljeJMBG = Convert.ToInt32(CS.AppSettings["poljeJMBG"]);
                poljeIme = Convert.ToInt32(CS.AppSettings["poljeIme"]);
                poljeSifra = Convert.ToInt32(CS.AppSettings["poljeSifra"]);
                poljePeriodOD = Convert.ToInt32(CS.AppSettings["poljePeriodOD"]);
                poljePeriodDO = Convert.ToInt32(CS.AppSettings["poljePeriodDO"]);
                poljeBruto = Convert.ToInt32(CS.AppSettings["poljeBruto"]);
                poljeTOsigPorez = Convert.ToInt32(CS.AppSettings["poljeTOsigPorez"]);
                poljeTOsigPIO = Convert.ToInt32(CS.AppSettings["poljeTOsigPIO"]);
                poljeTOsigRFZO = Convert.ToInt32(CS.AppSettings["poljeTOsigRFZO"]);
                poljeTOsigZZZ = Convert.ToInt32(CS.AppSettings["poljeTOsigZZZ"]);
                poljeTIsplatPIO = Convert.ToInt32(CS.AppSettings["poljeTIsplatPIO"]);
                poljeTIsplatRFZO = Convert.ToInt32(CS.AppSettings["poljeTIsplatRFZO"]);
                poljeTIsplatZZZ = Convert.ToInt32(CS.AppSettings["poljeTIsplatZZZ"]);
                poljeTIsplatFondRada = Convert.ToInt32(CS.AppSettings["poljeTIsplatFondRada"]);

                formatDatuma = CS.AppSettings["formatDatuma"];
                poljeGodinaPosebno = Convert.ToBoolean(CS.AppSettings["poljeGodinaPosebno"]);
                poljeGodina = Convert.ToInt32(CS.AppSettings["poljeGodina"]);

                MessageBox.Show("Uspješno izmijenjeni podaci zaglavlja!");
            }
            catch (System.IO.IOException exc)
            {
                Console.WriteLine(exc.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnValidate_Click(object sender, EventArgs e)
        {
            var test = "ioppd-schema.xsd";
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CloseInput = true;
            settings.ValidationEventHandler += ValidationCallBack;

            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, test);
            settings.ValidationFlags =
                XmlSchemaValidationFlags.ReportValidationWarnings |
                XmlSchemaValidationFlags.ProcessIdentityConstraints |
                XmlSchemaValidationFlags.ProcessInlineSchema |
                XmlSchemaValidationFlags.ProcessSchemaLocation;

            StringReader r = new StringReader(rtbXML.Text);

            using (XmlReader validatingReader = XmlReader.Create(r, settings))
            {
                while (validatingReader.Read()) { /* TODO dio za validaciju */ }
            }
        }

        private void btnSacuvajXML_Click(object sender, EventArgs e)
        {
            string filePath = "IOPPD_" + txtMjesec.Text + "_" + txtGodina.Text + ".xml";
            string argument = @"/select, " + filePath;
            try
            {
                File.WriteAllText(filePath, rtbXML.Text);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
            finally
            {
                Process.Start("explorer.exe", argument);
            }
        }

        private void btnSacuvajConfig_Click(object sender, EventArgs e)
        {
            SacuvajIzmjeneConfiga();
        }

        private void btnMinimize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
    }
}
